import csv
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import norm, pinv


def Read_csv(csvname, st=0):
    with open(csvname) as f:
        text = f.readlines()
    datax = []
    datay = []
    for line in text[st:]:
        rows = line.strip().split(',')
        rows = np.array(rows)
        datax.append(rows[:-1])
        datay.append(rows[len(rows)-1])
    datax = np.array(datax, dtype=float)#[:100]
    datay = np.array(datay, dtype=float)#[:100]
    return (datax,datay)

def Read_csv_inrows(csvname, rowss, st = 0):
    with open(csvname) as f:
        text = f.readlines()
    datax = []
    for line in text[st:]:
        rows = line.strip().split(',')
        rows = np.array(rows)
        if rows[0]!='' and rows[0]!='-' and rows[0]!='Theta[deg]':
            datax.append(rows)
    datax = np.array(datax, dtype=float)
    return datax[:,rowss]

if __name__ == "__main__":
    XX,y=Read_csv(r'abcd.csv')
    x=XX[:,0]
    print(XX)
    print(y)
    import matplotlib.pyplot as plt
    import numpy as np

    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False

    an = np.polyfit(x, y, 18)        # 用3次多项式拟合
    # 如果源数据点不够要自己扩充，否则直接使用源数据点即可
    x1 = np.arange(2, 6, 0.01)  # 画曲线用的数据点
    yvals = np.polyval(an, x1)      # 根据多项式系数计算拟合后的值

    # 画图
    plt.plot(x, y, '*', label='原数据点')
    plt.plot(x1, yvals, 'r', label='拟合后')
    plt.xlabel('x 轴')
    plt.ylabel('y 轴')
    plt.legend(loc=4)               # 指定legend的位置
    plt.title('曲线拟合')
    plt.show()
    for i in range(len(x1)):
        with open('abcde.csv', 'a', encoding='utf-8', newline='') as f:
            write = csv.writer(f)  # 创建writer对象
            write.writerow([x1[i],yvals[i]])





